package com.cuitrip.config;

import com.cuitrip.mode.Commit;
import com.cuitrip.mode.Language;
import com.cuitrip.mode.Rule;
import com.cuitrip.util.PrintUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * Created by MiJack on 2015/11/21.
 */
public class Config {
    private InputConfig inputConfig;
    private OutputConfig outputConfig;

    public InputConfig getInputConfig() {
        return inputConfig;
    }

    public OutputConfig getOutputConfig() {
        return outputConfig;
    }

    private void readConfig(File configFile) throws DocumentException {
        SAXReader reader = new SAXReader();
        //读取文件 转换成Document
        Document document = reader.read(configFile);
        //获取根节点元素对象
        Element root = document.getRootElement();
        Element input = root.element("input");
        Element output = root.element("output");
        inputConfig = InputConfig.build(input);
        outputConfig = OutputConfig.build(output);
        PrintUtil.print(inputConfig);
        PrintUtil.print(outputConfig);
    }

    private Config() {
    }

    private static Config ourInstance = new Config();

    public synchronized static Config getInstance(File configFile) throws DocumentException {
        synchronized (Config.class) {
            if (ourInstance == null) {
                ourInstance = new Config();
            }
        }
        ourInstance.readConfig(configFile);
        return ourInstance;
    }

    public String getFileEncoding() {
        return inputConfig.getFileEncoding();
    }

    public String getFileName() {
        return inputConfig.getFileName();
    }

    public List<Rule> getRuleList() {
        return outputConfig.getList();
    }

    public Map<Integer, Language> getLanguageMap() {
        return inputConfig.getMap();
    }

    public boolean isOldKeyEnable() {
        return inputConfig.getOldKey() == -1;
    }


    public int getKeyIndex() {
        return inputConfig.getKey();
    }

    public int getOldKeyIndex() {
        return inputConfig.getOldKey();
    }


    public int getCommitIndex() {
        return inputConfig.getCommit();
    }


    public List<Commit> getComitModes() {
        return inputConfig.getCommits();
    }

    public boolean isWindowsFile() {
        String result = inputConfig.getIsWindowFile();
        if ("true".equals(result.toLowerCase()) || "1".equals(result)) {
            return true;
        }
        return false;
    }
}
